package com.atbeijing.gmall.realtime.utils;

import com.alibaba.fastjson.JSONObject;
import com.atbeijing.gmall.realtime.common.GmallConfig;
import org.apache.commons.beanutils.BeanUtils;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 操作Phoenix的工具类
 */
public class PhoenixUtil {

    private static Connection conn;

    //初始化连接
    private static void queryInit() throws Exception {
        //加载驱动
        Class.forName(GmallConfig.PHOENIX_DRIVER);
        //获取连接
        conn = DriverManager.getConnection(GmallConfig.PHOENIX_SERVER);
        //连接数据库
        conn.setSchema(GmallConfig.HBASE_SCHEMA);
    }

    /**
     * 从Phoenix中查询查询数据
     * @param sql 查询的sql
     * @param cla 返回的包装类型
     * @param <T>
     * @return
     */
    public static <T> List<T> queryList(String sql,Class<T> cla){
        ArrayList<T> resultList = new ArrayList<>();
        PreparedStatement ps=null;
        ResultSet result=null;
        try {
            if(conn==null){
                queryInit();
            }
            //创建数据库操作对象
            ps = conn.prepareStatement(sql);
            //执行sql
            result = ps.executeQuery();
            //获取结果集元数据信息,包含字段信息
            ResultSetMetaData metaData = result.getMetaData();
            //处理结果集,result为一条一条数据
            while (result.next()){
                //创建用于封装的对象
                T obj = cla.newInstance();
                for (int i = 1; i <=metaData.getColumnCount(); i++) {
                    //获取字段名
                    String columnName = metaData.getColumnName(i);
                    Object value = result.getObject(i);
                    BeanUtils.setProperty(obj,columnName,value);
                }
                resultList.add(obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("从Phoenix中查询数据失败");
        }finally {
            //释放资源
            if(result!=null){
                try {
                    result.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(ps!=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return resultList;
    }



    public static void main(String[] args) {
//        List<JSONObject> list = queryList("select * from GMALL1116_REALTIME.DIM_BASE_PROVINCE", JSONObject.class);
//        System.out.println(list);
    }
}
